package direct;

import Constant.constant;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建链接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //2.设置参数
        factory.setHost(constant.localhost);
        factory.setPort(constant.port);
        factory.setVirtualHost(constant.VirtuHost);
        factory.setUsername(constant.UserName);
        factory.setPassword(constant.Password);
        //3.创立链接
        Connection connection=factory.newConnection();
        //4.创建channel信道
        Channel channel=connection.createChannel();

        //声明交换机
        channel.exchangeDeclare(constant.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT,true);
        //声明队列
//        queue:队列名称
//        duarble:是否持久化 持久化的队列会落盘，服务器重启，消息不丢失
//        exclusive:是否独占
//        autoDelete：当没有Consumer时，自动删除掉
        channel.queueDeclare(constant.DIRECT_QUEUE1,true,false,false,null);
        channel.queueDeclare(constant.DIRECT_QUEUE2,true,false,false,null);

        //交换机和队列绑定 定向
//        含义：路由键 或 绑定键
//        说明：这是最重要的参数，决定了消息如何从交换机路由到队列
//        特别说明：对于 Fanout 类型交换机，这个参数被忽略，所以用空字符串
        channel.queueBind(constant.DIRECT_QUEUE1,constant.DIRECT_EXCHANGE,"a");
        channel.queueBind(constant.DIRECT_QUEUE2,constant.DIRECT_EXCHANGE,"a");
        channel.queueBind(constant.DIRECT_QUEUE2,constant.DIRECT_EXCHANGE,"b");
        channel.queueBind(constant.DIRECT_QUEUE2,constant.DIRECT_EXCHANGE,"c");

        //发布消息
        String msg="hello direct,my routingkey is a...";
//        第二个参数： 定向
//            含义：路由键
//        说明：用于指定消息的路由规则
//        特别说明：对于 Fanout 类型交换机，这个参数被忽略，所以用空字符串
//        第三个参数：null
//        含义：消息属性
//        说明：用于设置消息的额外属性和配置
        channel.basicPublish(constant.DIRECT_EXCHANGE,"a",null,msg.getBytes(StandardCharsets.UTF_8));
        String msg_b="hello direct,my routingkey is b...";
        channel.basicPublish(constant.DIRECT_EXCHANGE,"b",null,msg_b.getBytes(StandardCharsets.UTF_8));
        String msg_c="hello direct,my routingkey is c...";
        channel.basicPublish(constant.DIRECT_EXCHANGE,"c",null,msg_c.getBytes(StandardCharsets.UTF_8));

        System.out.println("消息发送成功");

        channel.close();
        connection.close();
    }
}
